package com.ssl.pdf.image;

import com.ssl.pdf.util.ImageUtil;
import org.apache.commons.io.FileUtils;
import org.apache.fontbox.ttf.TTFParser;
import org.apache.fontbox.ttf.TrueTypeFont;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.rendering.PDFRenderer;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * 描述：
 *
 * @author ssl
 * @create 2021/7/9 0009.
 */
public class PdfToImg {
    private static String TTFPATH = "E:\\test\\STSONG-light.ttf";

    private static String PDFPATH = "E:\\test\\pdf\\sy-result.pdf";

    private static String IMGRESULTPATH = "E:\\test\\image\\r1.JPG";

    public static void main(String[] args) throws Exception {

        toImg(FileUtils.readFileToByteArray(new File(PDFPATH)));
    }

    public static void toImg(byte[] pdf) throws Exception {
        PDDocument document = Loader.loadPDF(pdf);


        PDFRenderer pdfRenderer = new MyPDFRenderer(document);


        BufferedImage bufferedImage = pdfRenderer.renderImage(0);

        byte[] img = ImageUtil.bufferedImageToBytes(bufferedImage, "JPG");

        FileUtils.writeByteArrayToFile(new File(IMGRESULTPATH), img);
    }


    public static TrueTypeFont getTTF(String ttfFontPath) throws IOException {
        TTFParser ttfParser = new TTFParser();

        return ttfParser.parse(ttfFontPath);
    }


    private static class MyPDFRenderer extends PDFRenderer {


        public MyPDFRenderer(PDDocument document) throws IOException {
            super(document);

            TrueTypeFont trueTypeFont = getTTF(TTFPATH);
            PDFont formFont = PDType0Font.load(document, trueTypeFont, false);
            COSBase cosBase = COSName.FONT;
            COSObject cosObject = new COSObject(cosBase);

            document.getResourceCache().put(cosObject, formFont);

            System.out.println(document.getResourceCache().getFont(cosObject).getName());
        }
    }
}
